package com.yueshop.coupon.service.impl;

import com.yueshop.coupon.entity.SeckillSkuRelationEntity;
import com.yueshop.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.common.utils.Query;

import com.yueshop.coupon.dao.SeckillSessionDao;
import com.yueshop.coupon.entity.SeckillSessionEntity;
import com.yueshop.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {


    @Autowired
    SeckillSkuRelationService skuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }
    //获取最今三天要参与秒杀的商品
    @Override
    public List<SeckillSessionEntity> getLatest3DaysSession() {
        List<SeckillSessionEntity> seckillSessions = baseMapper.selectList(new QueryWrapper<SeckillSessionEntity>().between("start_time", getStartTime(), getEndTime()));
        if(seckillSessions!=null&& seckillSessions.size()>0){
            List<SeckillSessionEntity> promotion_session_id = seckillSessions.stream().map(seckillSessionEntity -> {
                List<SeckillSkuRelationEntity> seckillSkus = skuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", seckillSessionEntity.getId()));
                seckillSessionEntity.setSeckillSkus(seckillSkus);
                return seckillSessionEntity;
            }).collect(Collectors.toList());

            return promotion_session_id;
        }
        return null;
    }

    //获取最今三天的开始时间
    private String getStartTime(){
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        LocalDateTime start = LocalDateTime.of(now, min);
        return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    //获取最今三天的结束时间
    private String getEndTime(){
        LocalDate days = LocalDate.now().plusDays(2);
        LocalTime max = LocalTime.MAX;
        LocalDateTime end = LocalDateTime.of(days, max);
        return end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}